package com.atguigu.flink.chapter05.transform;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lzc
 * @Date 2022/7/5 8:57
 */
public class Flink09_Reduce {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        // select id, sum(vc) from .. group by id
        env
            .readTextFile("input/sensor.txt")
            .map(new MapFunction<String, WaterSensor>() {
                @Override
                public WaterSensor map(String value) throws Exception {
                    String[] data = value.split(",");
                
                
                    return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
                }
            })
            .keyBy(WaterSensor::getId)
            .reduce(new ReduceFunction<WaterSensor>() {
                // value1: 上次聚合的结果
                // value2:当前参与聚合的元素
                // 某个key第一个元素来的时候, 这个方法不执行
                @Override
                public WaterSensor reduce(WaterSensor value1,
                                          WaterSensor value2) throws Exception {
//                    System.out.println(value1.getId());
//                    value1.setVc(value1.getVc() + value2.getVc());
//                    value1.setTs(value1.getTs() + value2.getTs());
                    value1.setVc(Math.max(value1.getVc(), value2.getVc()));
                    return value1;
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
/*
简单聚合算子:
sum max min

maxBy 和 minBy


 */
